package com.keter.gateway.config;

import com.keter.gateway.filters.CustomGatewayFilterFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Mono;

/**
 * Created by gulx@neusoft.com on 2019/7/29.
 */
@Configuration
public class GatewayConfig {
    private static final Logger logger = LoggerFactory.getLogger(GatewayConfig.class);
    private static final String ELAPSED_TIME_BEGIN = "elapsedTimeBegin";

    @Bean
    @Order(-100)
    public GlobalFilter elapseFilter() {
        return (exchange, chain) -> {
            logger.info("ip:{}, uri:{}, params:{}",
                    exchange.getRequest().getRemoteAddress().getAddress().getHostAddress(),
                    exchange.getRequest().getURI().getRawPath(),
                    exchange.getRequest().getQueryParams());
            exchange.getAttributes().put(ELAPSED_TIME_BEGIN, System.currentTimeMillis());
//            return chain.filter(exchange);
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                Long startTime = exchange.getAttribute(ELAPSED_TIME_BEGIN);
                if (startTime != null) {
                    StringBuilder sb = new StringBuilder(exchange.getRequest().getURI().getRawPath())
                            .append(": ")
                            .append(System.currentTimeMillis() - startTime)
                            .append("ms");
                    logger.info(sb.toString());
                }
            }));
        };
    }

}
